import os
import sys
import time
import shutil
import pymysql
import requests
import warnings
import datetime
import pandas as pd
import mysql.connector
from selenium import webdriver
from sqlalchemy import create_engine
from dbutils.pooled_db import PooledDB
from ssh_operate import get_web_password
from selenium.webdriver.common.by import By
from urllib.parse import quote_plus as urlquote
from selenium.webdriver.chrome.service import Service
from ssh_operate import modify_centos_date_close, set_reboot
from Algorithm_test import create_24h_dy_data_for_calc, execute_sql
from global_parameter import fs_voltage_transformer_configs, DB_NAME, chromedriver_path, txt_path, ip, os_password

# 忽略警告信息
warnings.filterwarnings('ignore')


class Logger(object):
    """
    封装Logger类，用于系统print的时候，自动写入到log文件中
    """

    def __init__(self, fileN='Default.log'):
        self.terminal = sys.stdout
        self.log = open(fileN, 'w')

    def write(self, message):
        '''print实际相当于sys.stdout.write'''
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass


sys.stdout = Logger('./logs/log.txt')  # 调用print时相当于Logger().write()
# 清空csv_results
shutil.rmtree("./csv_results")
shutil.rmtree("./txt_result")
os.mkdir("./csv_results")
os.mkdir("./txt_result")
print("清空csv_results文件夹")
print("清空txt_result文件夹")


def add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm=[]):
    """
    添加电压线路
    :param DB_HOST:
    :param DB_NAME:
    :param configs:
    :return:
    """
    POOL = PooledDB(creator=pymysql, maxconnections=6, mincached=2, maxcached=5, maxshared=3, blocking=True,
                    maxusage=None, setsession=[], ping=0, host=DB_HOST, port=3306, user='oetsky', password='Oetsky@123',
                    database=DB_NAME, charset='utf8')
    conn = POOL.connection()
    cursor = conn.cursor()

    cursor.execute("TRUNCATE fs_voltage_transformer;")
    print("已清空电压互感器信息表")

    for config in fs_voltage_transformer_configs:
        cursor.execute("INSERT INTO `fs_voltage_transformer` VALUES ({});".format(config))
        conn.commit()

    # transformer_coefficient = [150, 150, 150, 150, 150, 150]
    line = int(len(transformer_parm) / 3)
    for channel in range(line):
        cursor.execute(
            "UPDATE fs_voltage_transformer set rated_load={} where line_channel={} and phase_seq='A';".format(
                transformer_parm[channel * 3], channel + 1))
        cursor.execute(
            "UPDATE fs_voltage_transformer set rated_load={} where line_channel={} and phase_seq='B';".format(
                transformer_parm[channel * 3 + 1], channel + 1))
        cursor.execute(
            "UPDATE fs_voltage_transformer set rated_load={} where line_channel={} and phase_seq='C';".format(
                transformer_parm[channel * 3 + 2], channel + 1))
        conn.commit()
    cursor.close()
    conn.close()


def get_cookie(browser, ip, port, username, password):
    """
    使用selenium登录网页，获取cookie，供后续接口调用
    :param browser:
    :param ip:
    :param port:
    :param username:
    :param password:
    :return:
    """
    browser.get("http://{}:{}/login".format(ip, port))
    time.sleep(1)
    browser.find_element(By.NAME, 'username').send_keys(username)  # 填入用户名
    time.sleep(1)
    browser.find_element(By.NAME, 'password').send_keys(password)  # 填入密码
    time.sleep(1)
    browser.find_element(By.ID, "btnSubmit").click()  # 填入密码
    cookies_list = browser.get_cookies()
    cookie_value = cookies_list[0].get("value")
    print(cookie_value)
    time.sleep(1)
    return cookie_value


def time_drive_task(ip, port, cookie_value, startTime="", endTime=""):
    """
    触发时间驱动计算电压数据
    :param ip:
    :param port:
    :param cookie_value:
    :return:
    """
    headers = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection": "keep-alive",
        "Content-Length": "0",
        "Cookie": "JSESSIONID={}".format(cookie_value),
        "Host": "{}:{}".format(ip, port),
        "Origin": "http://{}:{}".format(ip, port),
        "Referer": "http://{}:{}/monitor/job".format(ip, port),
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.44",
        "X-Requested-With": "XMLHttpRequest"
    }
    try:
        body = {'startTime': startTime, 'endTime': endTime}  # 参数为dict形式
        print(body)
        requests.post("http://{}:{}/timeDrivenTask/taskService".format(ip, port), headers=headers, timeout=5, data=body)
    except:
        pass
    # print(res)
    # print("请求定时任务返回状态码：{}".format(res.status_code))get_cookiest
    # assert res.status_code == 200


def stop_calc(ip, port, username, password):
    """
    触发时间驱动计算电压数据
    :param ip:
    :param port:
    :param cookie_value:
    :return:
    """
    service = Service(chromedriver_path)
    option = webdriver.ChromeOptions()
    # 不弹出chrome浏览器
    option.add_argument("headless")
    browser = webdriver.Chrome(service=service, options=option)
    cookie_value = get_cookie(browser, ip, port, username, password)
    browser.close()

    headers = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection": "keep-alive",
        "Content-Length": "0",
        "Cookie": "JSESSIONID={}".format(cookie_value),
        "Host": "{}:{}".format(ip, port),
        "Origin": "http://{}:{}".format(ip, port),
        "Referer": "http://{}:{}/monitor/job".format(ip, port),
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.44",
        "X-Requested-With": "XMLHttpRequest"
    }
    try:
        requests.post("http://{}:{}/timeDrivenTask/stopCalculate".format(ip, port), headers=headers, timeout=5)
    except:
        pass

    # 停止计算超时时间60分钟
    for i in range(6 * 60):
        res_str = get_calc_status(ip, port, cookie_value)
        if res_str == "false":
            break
        if i == 0 and res_str == "true":
            truncate_mysql_tables(ip, DB_NAME)
        time.sleep(10)
        print("停止计算中，等待计算完成，已等待时间：{}".format((i + 1) * 10))


def get_calc_status(ip, port, cookie_value):
    """
    触发时间驱动计算电压数据
    :param ip:
    :param port:
    :param cookie_value:
    :return:
    """
    headers = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection": "keep-alive",
        "Content-Length": "0",
        "Cookie": "JSESSIONID={}".format(cookie_value),
        "Host": "{}:{}".format(ip, port),
        "Origin": "http://{}:{}".format(ip, port),
        "Referer": "http://{}:{}/monitor/job".format(ip, port),
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.44",
        "X-Requested-With": "XMLHttpRequest"
    }
    try:
        res = requests.post("http://{}:{}/timeDrivenTask/getCalculateStatus".format(ip, port), headers=headers,
                            timeout=5)
    except:
        pass
    res_str = str(res.content, encoding="utf-8")
    # print(res_str)
    return res_str


def add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data):
    """
    添加电压线路
    :param DB_HOST:
    :param DB_NAME:
    :param channel_config:
    :return:
    """
    POOL = PooledDB(creator=pymysql, maxconnections=6, mincached=2, maxcached=5, maxshared=3, blocking=True,
                    maxusage=None, setsession=[], ping=0, host=DB_HOST, port=3306, user='oetsky', password='Oetsky@123',
                    database=DB_NAME, charset='utf8')
    conn = POOL.connection()
    cursor = conn.cursor()

    cursor.execute("TRUNCATE dv_voltage_channel;")
    cursor.execute("TRUNCATE dv_voltage_line_group_channel;")
    cursor.execute("TRUNCATE algo_config;")
    print("已清空电压线路配置表")
    print("已清空电压线路组通道关联表")
    print("已清空算法配置表")

    cursor.execute("TRUNCATE da_voltage_data_temp;")
    print("已清空半年数据表")
    cursor.execute("TRUNCATE err_voltage_error;")
    print("已清空误差计算数据表")
    cursor.execute("TRUNCATE err_voltage_status;")
    print("已清空数据预处理状态标记表")
    cursor.execute("TRUNCATE err_voltage_avg;")
    print("已清空误差计算均值表")
    cursor.execute("TRUNCATE err_voltage_slide_window;")
    print("已清空误差计算滑窗表")

    cursor.execute("TRUNCATE err_voltage_error_pile;")
    cursor.execute("TRUNCATE err_voltage_matrix_status;")
    cursor.execute("TRUNCATE err_voltage_pre_pile_record;")
    cursor.execute("TRUNCATE err_voltage_dynamic_slide_window;")

    for config in channel_config:
        cursor.execute("INSERT INTO `dv_voltage_channel` VALUES ({});".format(config))
        conn.commit()
    for config_group in channel_config_group:
        cursor.execute("INSERT INTO `dv_voltage_line_group_channel` VALUES ({});".format(config_group))
        conn.commit()
    for algo_config in algo_config_data:
        cursor.execute("INSERT INTO `algo_config` VALUES ({});".format(algo_config))
        conn.commit()
    cursor.close()
    conn.close()


def truncate_mysql_tables(DB_HOST, DB_NAME):
    """
    添加电压线路
    :param DB_HOST:
    :param DB_NAME:
    :param channel_config:
    :return:
    """
    POOL = PooledDB(creator=pymysql, maxconnections=6, mincached=2, maxcached=5, maxshared=3, blocking=True,
                    maxusage=None, setsession=[], ping=0, host=DB_HOST, port=3306, user='oetsky', password='Oetsky@123',
                    database=DB_NAME, charset='utf8')
    conn = POOL.connection()
    cursor = conn.cursor()

    cursor.execute("TRUNCATE dv_voltage_channel;")
    cursor.execute("TRUNCATE dv_voltage_line_group_channel;")
    cursor.execute("TRUNCATE algo_config;")
    cursor.execute("TRUNCATE fs_voltage_transformer;")

    cursor.execute("TRUNCATE da_voltage_data_temp;")
    cursor.execute("TRUNCATE err_voltage_error;")
    cursor.execute("TRUNCATE err_voltage_status;")
    cursor.execute("TRUNCATE err_voltage_avg;")
    cursor.execute("TRUNCATE err_voltage_slide_window;")
    cursor.execute("TRUNCATE err_voltage_error_pile;")
    cursor.execute("TRUNCATE err_voltage_matrix_status;")
    cursor.execute("TRUNCATE err_voltage_pre_pile_record;")
    cursor.execute("TRUNCATE err_voltage_dynamic_slide_window;")
    print("停止计算，清空所有表")

    cursor.close()
    conn.close()


def start_time_task(ip, port, username, password, min_time, max_time):
    """
    启动定时任务
    :param ip:
    :param port:
    :param username:
    :param password:
    :return:
    """
    option = webdriver.ChromeOptions()
    service = Service(chromedriver_path)
    # 不弹出chrome浏览器
    option.add_argument("headless")
    browser = webdriver.Chrome(service=service, options=option)
    cookie_value = get_cookie(browser, ip, port, username, password)
    time_drive_task(ip, port, cookie_value, min_time, max_time)
    browser.close()


def wait_task_done(DB_HOST, DB_NAME, datatime_max, is_cal_today=False):
    """
    等待定时任务完成
    :param DB_HOST:
    :param DB_NAME:
    :param is_cal_today:
    :return:
    """
    # 计算超过十分钟停止
    for i in range(10 * 6):
        con_user = pymysql.connect(host=DB_HOST, port=3306, user="oetsky", password='Oetsky@123', db=DB_NAME,
                                   charset='utf8')
        if is_cal_today:
            str_today = datetime.date.today().strftime("%Y-%m-%d")
            df_err_voltage_error = pd.read_sql(
                "SELECT * FROM err_voltage_error where calculate_time like'{}%';".format(str_today), con_user)
        else:
            df_err_voltage_error = pd.read_sql("SELECT * FROM err_voltage_error;", con_user)
        calculate_time_list = df_err_voltage_error["calculate_time"].tolist()
        final_time = (datatime_max + datetime.timedelta(hours=23) + datetime.timedelta(minutes=59)).strftime(
            "%Y-%m-%d %H:%M:%S")
        calculate_time_list = [i.strftime("%Y-%m-%d %H:%M:%S") for i in calculate_time_list]

        if final_time not in calculate_time_list:
            time.sleep(10)
            if calculate_time_list:
                print("定时任务已经执行时间：{}s,需要生成最后时间：{},实际当前生成最后时间：{}".format(
                    (i + 1) * 10, final_time, calculate_time_list[-1]))
            else:
                print("定时任务已经执行时间：{}s,需要生成最后时间：{},实际暂无数据产生".format((i + 1) * 10, final_time))
            con_user.close()
            continue
        else:
            time.sleep(10)
            con_user.close()
            break


def read_xlsx_append_sql(ip, DB_NAME):
    """
    读取xlsx文件，插入到sql中
    :param DB_HOST:
    :param DB_NAME:
    :return:
    """
    pd_data = pd.read_excel("./da_voltage_data_temp_比差为0.xlsx")
    pre_time = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    for i in range(len(pd_data)):
        str_hms = pd_data["collect_time"][i].strftime(" %H:%M:%S")
        pd_data["collect_time"][i] = datetime.datetime.strptime(pre_time + str_hms, "%Y-%m-%d %H:%M:%S")
        pd_data["create_time"][i] = datetime.datetime.strptime(pre_time + str_hms, "%Y-%m-%d %H:%M:%S")

    userName = "oetsky"
    password = "Oetsky@123"
    dbHost = ip
    dbPort = 3306
    dbName = DB_NAME
    DB_CONNECT = f'mysql+pymysql://{userName}:{urlquote(password)}@{dbHost}:{dbPort}/{dbName}?charset=utf8'
    engine = create_engine(
        DB_CONNECT,
        max_overflow=50,  # 超过连接池大小外最多创建的连接
        pool_size=50,  # 连接池大小
        pool_timeout=5,  # 池中没有线程最多等待的时间，否则报错
        pool_recycle=-1,  # 多久之后对线程池中的线程进行一次连接的回收（重置）
        # encoding='utf-8',
        echo=False
    )
    pd_data.to_sql(name="da_voltage_data_temp", con=engine, if_exists="replace", index=False)


def export_csv(DB_HOST, DB_NAME, scene_name):
    """
    读取SQL，导出csv
    :param DB_HOST:
    :param DB_NAME:
    :return:
    """
    os.mkdir("./csv_results/{}".format(scene_name))
    con_user = pymysql.connect(host=DB_HOST, port=3306, user="oetsky", password='Oetsky@123', db=DB_NAME,
                               charset='utf8')
    df_err_voltage_error = pd.read_sql("SELECT * FROM err_voltage_error;", con_user)
    # df_err_voltage_status = pd.read_sql("SELECT * FROM err_voltage_status;", con_user)
    df_err_voltage_slide_window = pd.read_sql("SELECT * FROM err_voltage_slide_window;", con_user)
    df_da_voltage_data_temp = pd.read_sql("SELECT * FROM da_voltage_data_temp;", con_user)
    df_err_voltage_error_pile = pd.read_sql("SELECT * FROM err_voltage_error_pile;", con_user)
    df_err_voltage_matrix_status = pd.read_sql("SELECT * FROM err_voltage_matrix_status;", con_user)
    df_err_voltage_pre_pile_record = pd.read_sql("SELECT * FROM err_voltage_pre_pile_record;", con_user)
    df_err_voltage_dynamic_slide_window = pd.read_sql("SELECT * FROM err_voltage_dynamic_slide_window;", con_user)
    con_user.close()

    str_now_time = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
    df_err_voltage_error.to_csv(
        "./csv_results/{}/{}_err_voltage_error_{}.csv".format(scene_name, scene_name, str_now_time))
    # df_err_voltage_status.to_csv(
    #     "./csv_results/{}/{}_df_err_voltage_status_{}.csv".format(scene_name, scene_name, str_now_time))
    df_err_voltage_slide_window.to_csv(
        "./csv_results/{}/{}_err_voltage_slide_window_{}.csv".format(scene_name, scene_name, str_now_time))
    df_da_voltage_data_temp.to_csv(
        "./csv_results/{}/{}_da_voltage_data_temp_{}.csv".format(scene_name, scene_name, str_now_time))
    df_err_voltage_error_pile.to_csv(
        "./csv_results/{}/{}_err_voltage_error_pile_{}.csv".format(scene_name, scene_name, str_now_time))
    df_err_voltage_matrix_status.to_csv(
        "./csv_results/{}/{}_err_voltage_matrix_status_{}.csv".format(scene_name, scene_name, str_now_time))
    df_err_voltage_pre_pile_record.to_csv(
        "./csv_results/{}/{}_err_voltage_pre_pile_record_{}.csv".format(scene_name, scene_name, str_now_time))
    df_err_voltage_dynamic_slide_window.to_csv(
        "./csv_results/{}/{}_err_voltage_dynamic_slide_window_{}.csv".format(scene_name, scene_name, str_now_time))
    df_err_voltage_error.sort_values(by="channel_num", inplace=True, ascending=True)
    return df_err_voltage_error


def wirte_txt(content):
    """
    写入结果到txt
    """
    with open(txt_path, "a") as f:
        f.write(content)


def check_test_result(scene_name, df, list_ratio, list_angle, list_status, list_msg):
    sql_ratio = df["aa_ratio_error"].to_list() + df["bb_ratio_error"].to_list() + df["cc_ratio_error"].to_list()
    sql_angle = df["aa_angle_error"].to_list() + df["bb_angle_error"].to_list() + df["cc_angle_error"].to_list()
    sql_status = df["calculate_status"].to_list()
    sql_msg = df["calculate_msg"].to_list()
    print(sql_ratio)
    print(sql_angle)
    print(sql_status)
    print(sql_msg)
    result = "pass"

    if len(list_ratio) == len(sql_ratio) and len(list_angle) == len(sql_angle) and \
            len(list_status) == len(sql_status) and len(list_msg) == len(sql_msg):
        for index, ratio in enumerate(list_ratio):
            if ratio and ratio != sql_ratio[index]:
                result = "fail"
        for index, angle in enumerate(list_angle):
            if angle and angle != sql_angle[index]:
                result = "fail"
        for index, status in enumerate(list_status):
            if status and status != sql_status[index]:
                result = "fail"
        for index, msg in enumerate(list_msg):
            if msg and msg != sql_msg[index]:
                result = "fail"
    else:
        print("列表数据和SQL数据条数不对应")
        print(list_ratio, list_angle, list_status, list_msg)
        print(sql_ratio, sql_angle, sql_status, sql_msg)
        result = "fail"
    return result


def execute_sql_file(sql_path):
    # 建立数据库连接
    cnx = mysql.connector.connect(
        host=ip,
        user='oetsky',
        password='Oetsky@123',
        database=DB_NAME
    )

    # 创建游标对象
    cursor = cnx.cursor()

    # 读取.sql文件
    with open(sql_path, 'r', encoding="utf8") as sql_file:
        sql_statements = sql_file.read()

    # 执行SQL语句
    cursor.execute(sql_statements, multi=True)

    # 提交更改
    cnx.commit()

    # 关闭游标和数据库连接
    cursor.close()
    cnx.close()


def recover_database():
    """
    恢复数据表，解决表被删除后，截断报错问题
    :return:
    """
    try:
        execute_sql("DROP TABLE IF EXISTS `dv_voltage_line_group`;")
        execute_sql("DROP TABLE IF EXISTS `dv_voltage_line_group_channel`;")
    except:
        pass
    execute_sql_file("./sql_file/dv_voltage_line_group.sql")
    execute_sql("SET FOREIGN_KEY_CHECKS = 1;")
    execute_sql("INSERT INTO `dv_voltage_line_group` VALUES (1, 1, 1, '2023-07-18 19:40:59', NULL, '1');")

    execute_sql_file("./sql_file/dv_voltage_line_group_channel.sql")
    execute_sql("INSERT INTO `dv_voltage_line_group_channel` VALUES (1, 1, 5, 1);")
    execute_sql("INSERT INTO `dv_voltage_line_group_channel` VALUES (1, 2, 5, 1);")
    execute_sql("SET FOREIGN_KEY_CHECKS = 1;")


def all_flow(ip, port, username, DB_NAME, v_arg_list, scene_name, channel_config, channel_config_group,
             algo_config_data, transformer_parm, list_ratio, list_angle, list_status, list_msg, time_data=[-1, 24],
             v_220_all_ty=False, v_220_12_34_ty=False, start_day=-1, end_day=-1, update_sqls=[], is_append=False):
    """
    全流程测试
    :param ip:
    :param port:
    :param username:
    :param DB_NAME:
    :param v_arg_list:
    :param channel_config:
    :return:
    """
    start_time = (datetime.date.today() + datetime.timedelta(days=start_day)).strftime("%Y-%m-%d")
    end_time = (datetime.date.today() + datetime.timedelta(days=end_day)).strftime("%Y-%m-%d")
    result = "fail"
    try:
        print("{}：开始测试".format(scene_name))
        DB_HOST = ip

        # 获取站端网页每日密码
        password = get_web_password(ip, port=10088, username="oetsky", password=os_password)
        print("{} ：web端访问密码".format(ip), password)

        # 停止站端计算
        stop_calc(ip, port, username, password)

        # 第一步，添加线路数据
        add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm)
        add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data)
        print("第一步，添加线路数据完毕")

        # 第二步，生成并导入数据库数据
        pre_datetime = (datetime.date.today() + datetime.timedelta(days=time_data[0])).strftime("%Y-%m-%d %H:%M:%S")
        create_24h_dy_data_for_calc(p_datetime=pre_datetime, v_list=v_arg_list, time=time_data[1],
                                    v_220_all_ty=v_220_all_ty, v_220_12_34_ty=v_220_12_34_ty)
        if update_sqls:
            for update_sql in update_sqls:
                execute_sql(update_sql)
        print("第二步，生成并导入数据库数据完毕")

        # 第三步,修改数据库制造停电数据
        if is_append is True:
            read_xlsx_append_sql(DB_HOST, DB_NAME)
            print("第三步,添加三相不平衡数据完毕")

        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, start_time, end_time)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(end_time, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name)
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        result = check_test_result(scene_name, df_err_voltage_error, list_ratio, list_angle, list_status, list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")
    except Exception as e:
        print(e)
        print("出现异常：{}".format(scene_name))
    finally:
        wirte_txt(scene_name + ":" + result + "\r")


def all_flow_857(ip, port, username, DB_NAME, v_arg_list, scene_name, channel_config, channel_config_group,
                 algo_config_data, transformer_parm, list_ratio, list_angle, list_status, list_msg, time_data=[-1, 24],
                 v_220_all_ty=False, v_220_12_34_ty=False, start_day=-1, end_day=-1, update_sqls=[], is_append=False):
    """
    全流程测试
    :param ip:
    :param port:
    :param username:
    :param DB_NAME:
    :param v_arg_list:
    :param channel_config:
    :return:
    """
    today = datetime.date.today().strftime("%Y-%m-%d")
    yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    before_yesterday = (datetime.date.today() + datetime.timedelta(days=-2)).strftime("%Y-%m-%d")
    result1 = "fail"
    result2 = "fail"
    result3 = "fail"
    result4 = "fail"
    result5 = "fail"
    result6 = "fail"

    try:
        print("{}：开始测试".format(scene_name))
        DB_HOST = ip

        # 获取站端网页每日密码
        password = get_web_password(ip, port=10088, username="oetsky", password=os_password)
        print("{} ：web端访问密码".format(ip), password)

        # 停止站端计算
        stop_calc(ip, port, username, password)

        # 第一步，添加线路数据
        add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm)
        add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data)
        print("第一步，添加线路数据完毕")

        # 第二步，生成并导入数据库数据
        pre_datetime = (datetime.date.today() + datetime.timedelta(days=time_data[0])).strftime("%Y-%m-%d %H:%M:%S")
        create_24h_dy_data_for_calc(p_datetime=pre_datetime, v_list=v_arg_list, time=time_data[1],
                                    v_220_all_ty=v_220_all_ty, v_220_12_34_ty=v_220_12_34_ty)

        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_1")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result1 = check_test_result(scene_name + "_1", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        手动执行昨天采集数据的误差评估计算，查看电压互感器误差数据界面和数据库中err_voltage_error表
        """
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, yesterday, yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_2")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result2 = check_test_result(scene_name + "_2", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        修改低压线路为评估，手动执行今天采集数据的误差评估计算，查看电压互感器误差数据界面和数据库中err_voltage_error表
        """
        execute_sql("UPDATE dv_voltage_channel SET assess_status=1;")
        execute_sql("INSERT INTO `dv_voltage_line_group_channel` VALUES (1, 3, 4, 1);")
        execute_sql("INSERT INTO `dv_voltage_line_group_channel` VALUES (1, 4, 4, 1);")
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, today, today)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(today, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_3")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(today + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result3 = check_test_result(scene_name + "_3", df_err_voltage_error,
                                    [None, None, None, None, None, None, None, None, None, None, None, None],
                                    [None, None, None, None, None, None, None, None, None, None, None, None],
                                    ['0', '0', '0', '0'],
                                    ['正常评估', '正常评估', '正常评估', '正常评估'])
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        截断err_voltage_error表，修改低压的两条线路电压等级为220kV，是否评估为不评估，重复步骤1
        """
        execute_sql("TRUNCATE err_voltage_error;")
        execute_sql("UPDATE dv_voltage_channel SET channel_level=5,assess_status=0 WHERE channel_level=4;")
        execute_sql("DELETE FROM dv_voltage_line_group_channel WHERE channel_level=4;")
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_4")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result4 = check_test_result(scene_name + "_4", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        继续步骤4，截断err_voltage_error表，修改线路2是否评估为不评估，重复步骤1
        """
        execute_sql("TRUNCATE err_voltage_error;")
        execute_sql("UPDATE dv_voltage_channel SET assess_status=0 WHERE channel_num=2;")
        execute_sql("DELETE FROM dv_voltage_line_group_channel WHERE channel_num=2;")
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_5")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result5 = check_test_result(scene_name + "_5", df_err_voltage_error,
                                    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                                    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                                    ['5', '15', '15', '15'],
                                    ['同电压等级下并列运行线路过少', '未执行误差计算', '未执行误差计算',
                                     '未执行误差计算'])
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        继续步骤5，截断err_voltage_error表，修改线路1是否评估为不评估，重复步骤1
        """
        execute_sql("TRUNCATE err_voltage_error;")
        execute_sql("UPDATE dv_voltage_channel SET assess_status=0 WHERE channel_num=1;")
        execute_sql("DELETE FROM dv_voltage_line_group_channel WHERE channel_num=1;")
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_6")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result6 = check_test_result(scene_name + "_6", df_err_voltage_error,
                                    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                                    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                                    ['15', '15', '15', '15'],
                                    ['未执行误差计算', '未执行误差计算', '未执行误差计算', '未执行误差计算'])
        print("第六步，检查计算状态、比差、角差、计算说明完毕")
    except Exception as e:
        print(e)
        print("出现异常：{}".format(scene_name))
    finally:
        wirte_txt(scene_name + "_1:" + result1 + "\r")
        wirte_txt(scene_name + "_2:" + result2 + "\r")
        wirte_txt(scene_name + "_3:" + result3 + "\r")
        wirte_txt(scene_name + "_4:" + result4 + "\r")
        wirte_txt(scene_name + "_5:" + result5 + "\r")
        wirte_txt(scene_name + "_6:" + result6 + "\r")


def all_flow_858(ip, port, username, DB_NAME, v_arg_list, scene_name, channel_config, channel_config_group,
                 algo_config_data, transformer_parm, list_ratio, list_angle, list_status, list_msg, time_data=[-1, 24],
                 v_220_all_ty=False, v_220_12_34_ty=False, start_day=-1, end_day=-1, update_sqls=[], is_append=False):
    """
    全流程测试
    :param ip:
    :param port:
    :param username:
    :param DB_NAME:
    :param v_arg_list:
    :param channel_config:
    :return:
    """
    today = datetime.date.today().strftime("%Y-%m-%d")
    yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    before_yesterday = (datetime.date.today() + datetime.timedelta(days=-2)).strftime("%Y-%m-%d")
    result1 = "fail"
    result2 = "fail"
    result3 = "fail"
    result4 = "fail"
    try:
        print("{}：开始测试".format(scene_name))
        DB_HOST = ip

        # 获取站端网页每日密码
        password = get_web_password(ip, port=10088, username="oetsky", password=os_password)
        print("{} ：web端访问密码".format(ip), password)

        # 停止站端计算
        stop_calc(ip, port, username, password)

        # 第一步，添加线路数据
        add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm)
        add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data)
        print("第一步，添加线路数据完毕")

        # 第二步，生成并导入数据库数据
        pre_datetime = (datetime.date.today() + datetime.timedelta(days=time_data[0])).strftime("%Y-%m-%d %H:%M:%S")
        create_24h_dy_data_for_calc(p_datetime=pre_datetime, v_list=v_arg_list, time=time_data[1],
                                    v_220_all_ty=v_220_all_ty, v_220_12_34_ty=v_220_12_34_ty)

        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_1")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result1 = check_test_result(scene_name + "_1", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        手动执行昨天采集数据的误差评估计算，查看电压互感器误差数据界面和数据库中err_voltage_error表
        """
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, yesterday, yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_2")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result2 = check_test_result(scene_name + "_2", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        修改低压线路为评估，手动执行今天采集数据的误差评估计算，查看电压互感器误差数据界面和数据库中err_voltage_error表
        """
        execute_sql("UPDATE dv_voltage_channel SET assess_status=1;")
        execute_sql("INSERT INTO `dv_voltage_line_group_channel` VALUES (1, 3, 4, 1);")
        execute_sql("INSERT INTO `dv_voltage_line_group_channel` VALUES (1, 4, 4, 1);")
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, today, today)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(today, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_3")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(today + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result3 = check_test_result(scene_name + "_3", df_err_voltage_error,
                                    [None, None, None, None, None, None, None, None, None, None, None, None],
                                    [None, None, None, None, None, None, None, None, None, None, None, None],
                                    ['0', '0', '0', '0'],
                                    ['正常评估', '正常评估', '正常评估', '正常评估'])
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        截断err_voltage_error表，修改低压的两条线路电压等级为220kV，是否评估为不评估，重复步骤1
        """
        execute_sql("TRUNCATE err_voltage_error;")
        # execute_sql("UPDATE dv_voltage_channel SET channel_level=5;")
        execute_sql("UPDATE dv_voltage_channel SET channel_level=5,assess_status=0 WHERE channel_level=4;")

        execute_sql("DELETE FROM dv_voltage_line_group_channel WHERE channel_level=4;")
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_4")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result4 = check_test_result(scene_name + "_4", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")
    except Exception as e:
        print(e)
        print("出现异常：{}".format(scene_name))
    finally:
        wirte_txt(scene_name + "_1:" + result1 + "\r")
        wirte_txt(scene_name + "_2:" + result2 + "\r")
        wirte_txt(scene_name + "_3:" + result3 + "\r")
        wirte_txt(scene_name + "_4:" + result4 + "\r")


def all_flow_ILAE_861(ip, port, username, DB_NAME, v_arg_list, scene_name, channel_config, channel_config_group,
                      algo_config_data, transformer_parm, list_ratio, list_angle, list_status, list_msg,
                      time_data=[-1, 24], v_220_all_ty=False, v_220_12_34_ty=False, start_day=-1, end_day=-1,
                      update_sqls=[], is_append=False):
    """
    全流程测试
    :param ip:
    :param port:
    :param username:
    :param DB_NAME:
    :param v_arg_list:
    :param channel_config:
    :return:
    """
    # 恢复数据表，解决表被删除后，截断报错问题
    recover_database()

    today = datetime.date.today().strftime("%Y-%m-%d")
    yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    before_yesterday = (datetime.date.today() + datetime.timedelta(days=-2)).strftime("%Y-%m-%d")
    result1 = "fail"
    result2 = "fail"
    result3 = "fail"

    try:
        print("{}：开始测试".format(scene_name))
        DB_HOST = ip

        # 获取站端网页每日密码
        password = get_web_password(ip, port=10088, username="oetsky", password=os_password)
        print("{} ：web端访问密码".format(ip), password)

        # 停止站端计算
        stop_calc(ip, port, username, password)

        # 第一步，添加线路数据
        add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm)
        add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data)
        print("第一步，添加线路数据完毕")

        # 第二步，生成并导入数据库数据
        pre_datetime = (datetime.date.today() + datetime.timedelta(days=time_data[0])).strftime("%Y-%m-%d %H:%M:%S")
        create_24h_dy_data_for_calc(p_datetime=pre_datetime, v_list=v_arg_list, time=time_data[1],
                                    v_220_all_ty=v_220_all_ty, v_220_12_34_ty=v_220_12_34_ty)
        if update_sqls:
            for update_sql in update_sqls:
                execute_sql(update_sql)
        execute_sql("UPDATE algo_config SET line_group=1;")
        execute_sql("DROP TABLE IF EXISTS `dv_voltage_line_group`;")
        execute_sql("DROP TABLE IF EXISTS `dv_voltage_line_group_channel`;")

        print("第二步，生成并导入数据库数据完毕")

        # 第三步,修改数据库制造三相不平衡数据
        if is_append is True:
            read_xlsx_append_sql(DB_HOST, DB_NAME)
            print("第三步,添加三相不平衡数据完毕")

        # 计算前天的数据
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_1")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result1 = check_test_result(scene_name + "_1", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        计算昨天的数据
        """
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, yesterday, yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_2")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result2 = check_test_result(scene_name + "_2", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        计算今天的数据
        """
        # 恢复dv_voltage_line_group与dv_voltage_line_group数据表
        recover_database()

        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, today, today)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(today, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_3")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(today + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result3 = check_test_result(scene_name + "_3", df_err_voltage_error, [None, None, None, None, None, None],
                                    [None, None, None, None, None, None], ['0', '0'], ['正常评估', '正常评估'])
        print("第六步，检查计算状态、比差、角差、计算说明完毕")
    except Exception as e:
        print(e)
        print("出现异常：{}".format(scene_name))
    finally:
        wirte_txt(scene_name + "_1:" + result1 + "\r")
        wirte_txt(scene_name + "_2:" + result2 + "\r")
        wirte_txt(scene_name + "_3:" + result3 + "\r")


def all_flow_ILAE_860(ip, port, username, DB_NAME, v_arg_list, scene_name, channel_config, channel_config_group,
                      algo_config_data, transformer_parm, list_ratio, list_angle, list_status, list_msg,
                      time_data=[-1, 24],
                      v_220_all_ty=False, v_220_12_34_ty=False, start_day=-1, end_day=-1, update_sqls=[],
                      is_append=False):
    """
    全流程测试
    :param ip:
    :param port:
    :param username:
    :param DB_NAME:
    :param v_arg_list:
    :param channel_config:
    :return:
    """
    # 恢复数据表，解决表被删除后，截断报错问题
    recover_database()

    today = datetime.date.today().strftime("%Y-%m-%d")
    yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
    before_yesterday = (datetime.date.today() + datetime.timedelta(days=-2)).strftime("%Y-%m-%d")
    result1 = "fail"
    result2 = "fail"
    result3 = "fail"

    try:
        print("{}：开始测试".format(scene_name))
        DB_HOST = ip

        # 获取站端网页每日密码
        password = get_web_password(ip, port=10088, username="oetsky", password=os_password)
        print("{} ：web端访问密码".format(ip), password)

        # 停止站端计算
        stop_calc(ip, port, username, password)

        # 第一步，添加线路数据
        add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm)
        add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data)
        print("第一步，添加线路数据完毕")

        # 第二步，生成并导入数据库数据
        pre_datetime = (datetime.date.today() + datetime.timedelta(days=time_data[0])).strftime("%Y-%m-%d %H:%M:%S")
        create_24h_dy_data_for_calc(p_datetime=pre_datetime, v_list=v_arg_list, time=time_data[1],
                                    v_220_all_ty=v_220_all_ty, v_220_12_34_ty=v_220_12_34_ty)
        if update_sqls:
            for update_sql in update_sqls:
                execute_sql(update_sql)
        execute_sql("UPDATE algo_config SET algo_package=10;")
        print("第二步，生成并导入数据库数据完毕")

        # 第三步,修改数据库制造三相不平衡数据
        if is_append is True:
            read_xlsx_append_sql(DB_HOST, DB_NAME)
            print("第三步,添加三相不平衡数据完毕")

        # 计算前天的数据
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, before_yesterday, before_yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(before_yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_1")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result1 = check_test_result(scene_name + "_1", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        计算昨天的数据
        """
        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, yesterday, yesterday)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(yesterday, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_2")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(yesterday + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result2 = check_test_result(scene_name + "_2", df_err_voltage_error, list_ratio, list_angle, list_status,
                                    list_msg)
        print("第六步，检查计算状态、比差、角差、计算说明完毕")

        """
        修改数据库中algo_config表中算法包字段为1（通用算法），手动执行今天采集数据的误差评估计算，查看电压互感器误差数据界面和数据库中err_voltage_error表
        """
        execute_sql("UPDATE algo_config SET algo_package=1;")

        # 第四步,触发定时任务
        start_time_task(ip, port, username, password, today, today)
        print("第四步,触发定时任务完毕")

        # 第五步，等待定时任务执行完成
        wait_task_done(DB_HOST, DB_NAME, datetime.datetime.strptime(today, "%Y-%m-%d"))
        print("第五步，等待定时任务执行完成")

        # 第六步，导出csv
        df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_3")
        print("第六步，导出csv完毕")

        # 第七步，检查计算状态、比差、角差、计算说明
        # print(df_err_voltage_error)
        df_err_voltage_error = df_err_voltage_error[
            df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(today + " 23:59:00",
                                                                                 "%Y-%m-%d %H:%M:%S")]
        result3 = check_test_result(scene_name + "_3", df_err_voltage_error, [None, None, None, None, None, None],
                                    [None, None, None, None, None, None], ['0', '0'], ['正常评估', '正常评估'])
        print("第六步，检查计算状态、比差、角差、计算说明完毕")
    except Exception as e:
        print(e)
        print("出现异常：{}".format(scene_name))
    finally:
        wirte_txt(scene_name + "_1:" + result1 + "\r")
        wirte_txt(scene_name + "_2:" + result2 + "\r")
        wirte_txt(scene_name + "_3:" + result3 + "\r")


# def all_flow_ILAE_859(ip, port, username, DB_NAME, v_arg_list, scene_name, channel_config, channel_config_group,
#                       algo_config_data, transformer_parm, list_ratio, list_angle, list_status, list_msg,
#                       time_data=[-1, 24],
#                       v_220_all_ty=False, v_220_12_34_ty=False, start_day=-1, end_day=-1, update_sqls=[],
#                       is_append=False):
#     """
#     全流程测试
#     :param ip:
#     :param port:
#     :param username:
#     :param DB_NAME:
#     :param v_arg_list:
#     :param channel_config:
#     :return:
#     """
#     # 恢复数据表，解决表被删除后，截断报错问题
#     recover_database()
#
#     after_tomorrow = (datetime.date.today() + datetime.timedelta(days=2)).strftime("%Y-%m-%d")
#     tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
#     today = datetime.date.today().strftime("%Y-%m-%d")
#     yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
#     before_yesterday = (datetime.date.today() + datetime.timedelta(days=-2)).strftime("%Y-%m-%d")
#
#     # try:
#     print("{}：开始测试".format(scene_name))
#     DB_HOST = ip
#
#     # 获取站端网页每日密码
#     password = get_web_password(ip, port=10088, username="oetsky", password=os_password)
#     print("{} ：web端访问密码".format(ip), password)
#
#     # 停止站端计算
#     stop_calc(ip, port, username, password)
#
#     # 第一步，添加线路数据
#     add_fs_voltage_transformer(DB_HOST, DB_NAME, transformer_parm)
#     add_voltage_channel(DB_HOST, DB_NAME, channel_config, channel_config_group, algo_config_data)
#     print("第一步，添加线路数据完毕")
#
#     # 第二步，生成并导入数据库数据
#     pre_datetime = (datetime.date.today() + datetime.timedelta(days=time_data[0])).strftime("%Y-%m-%d %H:%M:%S")
#     create_24h_dy_data_for_calc(p_datetime=pre_datetime, v_list=v_arg_list, time=time_data[1],
#                                 v_220_all_ty=v_220_all_ty, v_220_12_34_ty=v_220_12_34_ty)
#
#     # 设置首次误差评估时间为当天时间加两天的0点时间
#     execute_sql(
#         "UPDATE da_electric_dispose_time SET dispose_time='{} 00:00:00' WHERE data_type=6;".format(after_tomorrow))
#
#     # 修改站端时间为昨天的0点
#     # modify_centos_date_close(ip=ip, port=10088, username="oetsky", password=os_password,
#     #                          centos_date="{} 23:57:00".format(before_yesterday))
#
#     modify_centos_date_close(ip=ip, port=10088, username="oetsky", password=os_password,
#                              centos_date="{} 23:59:30".format(before_yesterday))
#     print(111)
#     time.sleep(60)
#     print("第二步，生成并导入数据库数据完毕")
#     # time.sleep(3)
#     # 重启站端
#     set_reboot(ip, port=10088, username="oetsky", password=os_password)
#     # 等待五分钟触发自动计算
#     time.sleep(5.5 * 60)
#
#     # 第六步，导出csv
#     df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_1")
#     print("第六步，导出csv完毕")
#
#     # 第七步，检查计算状态、比差、角差、计算说明
#     # print(df_err_voltage_error)
#     df_err_voltage_error = df_err_voltage_error[
#         df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(before_yesterday + " 23:59:00",
#                                                                              "%Y-%m-%d %H:%M:%S")]
#     check_test_result(scene_name + "_1", df_err_voltage_error, list_ratio, list_angle, list_status, list_msg)
#     print("第六步，检查计算状态、比差、角差、计算说明完毕")
#
#     """
#     修改站端时间为当天的0点，重启站端后等待0点5分的自动误差评估，查看电压互感器误差数据界面和数据库中err_voltage_error表
#     """
#     # 修改站端时间为当天的0点
#     modify_centos_date_close(ip=ip, port=port, username=username, password=password,
#                              centos_date="{} 00:00:00".format(today))
#     time.sleep(3)
#     print("第二步，生成并导入数据库数据完毕")
#     # 重启站端
#     set_reboot(ip, port=10088, username="oetsky", password=os_password)
#     # 等待五分钟触发自动计算
#     time.sleep(5 * 60)
#
#     # 第六步，导出csv
#     df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_2")
#     print("第六步，导出csv完毕")
#
#     # 第七步，检查计算状态、比差、角差、计算说明
#     # print(df_err_voltage_error)
#     df_err_voltage_error = df_err_voltage_error[
#         df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(yesterday + " 23:59:00",
#                                                                              "%Y-%m-%d %H:%M:%S")]
#     check_test_result(scene_name + "_2", df_err_voltage_error, list_ratio, list_angle, list_status, list_msg)
#     print("第六步，检查计算状态、比差、角差、计算说明完毕")
#
#     """
#     修改站端时间为当天加1天的0点，重启站端后等待0点5分的自动误差评估，查看电压互感器误差数据界面和数据库中err_voltage_error表
#     """
#     # 修改站端时间为当天加1天的0点
#     modify_centos_date_close(ip=ip, port=port, username=username, password=password,
#                              centos_date="{} 00:00:00".format(tomorrow))
#     time.sleep(3)
#     print("第二步，生成并导入数据库数据完毕")
#     # 重启站端
#     set_reboot(ip, port=10088, username="oetsky", password=os_password)
#     # 等待五分钟触发自动计算
#     time.sleep(5.5 * 60)
#
#     # 第六步，导出csv
#     df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_3")
#     print("第六步，导出csv完毕")
#
#     # 第七步，检查计算状态、比差、角差、计算说明
#     # print(df_err_voltage_error)
#     df_err_voltage_error = df_err_voltage_error[
#         df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(today + " 23:59:00",
#                                                                              "%Y-%m-%d %H:%M:%S")]
#     check_test_result(scene_name + "_3", df_err_voltage_error, list_ratio, list_angle, list_status, list_msg)
#     print("第六步，检查计算状态、比差、角差、计算说明完毕")
#
#     """
#     修改站端时间为当天加2天的0点，重启站端后等待0点5分的自动误差评估，查看电压互感器误差数据界面和数据库中err_voltage_error表
#     """
#     # 修改站端时间为当天加2天的0点
#     modify_centos_date_close(ip=ip, port=port, username=username, password=password,
#                              centos_date="{} 00:00:00".format(after_tomorrow))
#     time.sleep(3)
#     print("第二步，生成并导入数据库数据完毕")
#     # 重启站端
#     set_reboot(ip, port=10088, username="oetsky", password=os_password)
#     # 等待五分钟触发自动计算
#     time.sleep(5 * 60)
#
#     # 第六步，导出csv
#     df_err_voltage_error = export_csv(DB_HOST, DB_NAME, scene_name + "_4")
#     print("第六步，导出csv完毕")
#
#     # 第七步，检查计算状态、比差、角差、计算说明
#     # print(df_err_voltage_error)
#     df_err_voltage_error = df_err_voltage_error[
#         df_err_voltage_error['calculate_time'] == datetime.datetime.strptime(tomorrow + " 23:59:00",
#                                                                              "%Y-%m-%d %H:%M:%S")]
#     check_test_result(scene_name + "_4", df_err_voltage_error, list_ratio, list_angle, list_status, list_msg)
#     print("第六步，检查计算状态、比差、角差、计算说明完毕")
#     # except Exception as e:
#     #     print(e)
#     #     print("出现异常：{}".format(scene_name))


if __name__ == '__main__':
    pass
